import base64
import pickle
from rest_framework import serializers
from django_redis import  get_redis_connection
from rest_framework.response import Response
from goods.models import SKU


class CartCreateSerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    def validate(self, attrs):

        sku = SKU.objects.get(id=attrs['sku_id'])
        if sku is None:
            raise serializers.ValidationError('商品不存在!')

        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('库存不足!')

        return attrs

class CartListSerializer(serializers.ModelSerializer):

    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    class Meta:
        model = SKU
        fields = '__all__'

class CartDlelteSerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):

        sku = SKU.objects.get(id=attrs['sku_id'])
        if sku is None:
            raise serializers.ValidationError('商品不存在!')

        return attrs

class CartSelectedSerialier(serializers.Serializer):

    selected = serializers.BooleanField()
